<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use app\admin\model\NodeModel;
use app\admin\model\WebsetModel;
class Base extends Controller
{
    public function _initialize()
    {
        if(empty(session('username'))){

            $loginUrl = url('login/index');
            if(request()->isAjax()){
                return msg(111, $loginUrl, '登录超时');
            }

            $this->redirect($loginUrl);
        }

        // 检测权限
        $control = lcfirst(request()->controller());
        $action = lcfirst(request()->action());

        if(empty(authCheck($control . '/' . $action))){
            if(request()->isAjax()){
                return msg(403, '', '您没有权限');
            }

            $this->error('403 您没有权限');
        }

        $this->assign([
            'head'     => session('head'),
            'username' => session('username'),
            'rolename' => session('role'),
			'user_id'  => session('id')
        ]);

		$node = new NodeModel();
        $this->assign([
            'menu' => $node->getMenu(session('rule'))
        ]);

		$webset = new WebsetModel();
		$this->assign([
			'Webset'=>$webset->getInfo()
		]);
		$this->setLog();
    }

	/**
	 * [一维数组转树]
	 */
	public static function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'children') {
        $tree = $map = array();
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }
        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }
	/**
	 * [记录操作日志]
	 */
	public function setLog(){
        $operationController = strtolower($this->request->controller());
        $operationAction = strtolower($this->request->action());
        $operationUrl = $operationController . "/" . $operationAction;
        $operationName = DB::name('node')->where([
            'control_name'=>$operationController,
            'action_name'=>$operationAction
        ])->value('node_name');
        if($operationName != ''){
			$logData = [
	            'c_time' => time(),
	            'url' => $operationUrl,
	            'url_name' => $operationName,
	            'u_id' => session('id'),
	            'user_name' => session('username')
	        ];
	        DB::name('log')->insert($logData);
        }
	}

	public function getNameByTree($tree,$res=[],$prefix = ''){
		$str = '| - ';
		foreach($tree as $v){
			$res[] = [
				'id'=>$v['id'],
				'name'=>$str.$prefix.$v['name']
			];
			if(!empty($v['children'])){
				$prefix .= '- - ';
				$res = $this->getNameByTree($v['children'],$res,$prefix);
				$prefix = mb_substr($prefix,4,mb_strlen($prefix));
			}
		}
		return $res;
	}

	#-< XML2Arr and Arr2XML >------------------------------------------------------
	/**
	 * [数组转XML]
	 */
    public function Arr2XML($array,$root='root'){
        return $this->xml_encode($array, 'utf-8', $root);
    }
    public function xml_encode($array, $charset = 'utf-8', $root){
        $xml = '<?xml version="1.0" encoding="'.$charset.'"?>';
        $xml .= "<{$root}>";
        $xml .= $this->array_to_xml($array);
        $xml .= "</{$root}>";
        return $xml;
    }
    public function array_to_xml($array){
        if(is_object($array)){
            $array = get_object_vars($array);
        }
        $xml = '';
        foreach($array as $key => $value){
            $_tag = $key;
            $_id  = null;
            if(is_numeric($key)){
                $_tag = 'item';
                $_id  = ' id="' . $key . '"';
            }
            $xml .= "<{$_tag}{$_id}>";
            $xml .= (is_array($value) || is_object($value)) ? $this->array_to_xml($value) : ($value);
            $xml .= "</{$_tag}>";
        }
        return $xml;
    }

    /**
     * [XML转数组]
     */
    public function XML2Arr($xmlstring,$root='root'){
        return $this->xml_decode($xmlstring,$root);
    }
    public function xml_decode($xml, $root){
        $search = '/<(' . $root . ')>(.*)<\/\s*?\\1\s*?>/s';
        $array  = array();
        if(preg_match($search, $xml, $matches)){
            $array = $this->xml_to_array($matches[2]);
        }
        return $array;
    }
    public function xml_to_array($xml){
        $search = '/<(\w+)\s*?(?:[^\/>]*)\s*(?:\/>|>(.*?)<\/\s*?\\1\s*?>)/s';
        $array  = array ();
        if(preg_match_all($search, $xml, $matches)){
            foreach($matches[1] as $i => $key){
                $value = $matches[2][$i];
				if(preg_match_all($search, $value, $_matches)){
					if($key == 'item'){
						$array[] = $this->xml_to_array($value);
					}else{
						$array[$key] = $this->xml_to_array($value);
					}
					// $array[$key] = $this->xml_to_array($value);
                }else{
                    if('ITEM' == strtoupper($key)){
                        $array[] = html_entity_decode(str_replace( array( '<![CDATA[' , ']]>'), array( '' , '' ), $value ));
                    }else{
                        $array[$key] = html_entity_decode(str_replace( array( '<![CDATA[' , ']]>'), array( '' , '' ), $value ));
                    }
                }
            }
        }
        return $array;
    }
	#-< XML send >------------------------------------------------------
	public function sendXML2API($data="") {
		header("Content-Type:text/html;charset=UTF-8");
		$wsdl = DB::name('api_cfg')->where('remark','xml_url_phpapi')->value('val');
		libxml_disable_entity_loader(false);
		$opts = [
			'ssl' => [
				'verify_peer'          => false
			],
			'https' => [
				'curl_verify_ssl_peer'  => false,
            	'curl_verify_ssl_host'  => false
			]
		];
		$streamContext = stream_context_create($opts);
		$client = new \SoapClient($wsdl,['stream_context'=>$streamContext]);
		$param = ['in'=>$data];
		$result = $client->syncServiceStationOperation($param);
		return json_decode( json_encode($result),true);
	}
}
